﻿using System;
using System.Web;
using WAD.WEB.AppCode;
using WAD.DAL.Union;
using System.Collections.Generic;
using System.Data.SqlClient;
using WAD.Model;
using WAD.DAL;
using WAD.BLL;
using System.Text.RegularExpressions;
using System.Text;

namespace WAD.WEB.Admin.Ajax
{
    /// <summary>
    /// Agent 的摘要说明
    /// </summary>
    public class Agent : AdminAjax
    {
        public override void AjaxMethodDispatch(String identity)
        {
            switch (identity)
            {
                case "getlist": this.GetList(); break;
                case "add": this.Add(); break;
                case "get": this.Get(); break;
                case "detail": this.Detail(); break;
                case "getlist_recoad": this.GetList_Recoad(); break;
                case "getlist_jilu": this.GetList_JiLu(); break;
                case "pay": this.Pay(); break;
                case "getlist_tidan": this.GetList_Tidan(); break;
            }
        }
        [QD.Web.Ajax.AjaxMethod]
        public void GetList()
        {
            int id = Parse.Int("userid", 0);
            int page = Parse.Int("page", 1);
            int yewu_id = Parse.Int("yewu_id", 0);
            string siteName = Parse.String("sitename");

            string where = "userid_wjx>0 ";
            if (id > 0)
                where += " and userid_wjx=" + id;
            
            if (yewu_id > 0)
                where += " and AllotUserName=" + yewu_id;
            
            if (!string.IsNullOrEmpty(siteName))
                where += " and companyName like '%" + QD.WX.Utill.Util.FilterSql(siteName) + "%'";

            PageData dt = WAD.DAL.Union.DAOAgent.GetPageList("id,UserID,UserId_wjx,Balance,Phone,CellPhone,JoinTime,UpdateTime,CompanyName as sitename,Expiration_wjx as end_time", where, page, 20);
            JsonResult(0, "", dt);
        }

        [QD.Web.Ajax.AjaxMethod]
        public void Add()
        {
            int user_id = Parse.Int("user_id", 0);
            string sitename = Parse.String("sitename", "");
            string phone = Parse.String("phone", "");
            string mobile = Parse.String("mobile", "");
            string email = Parse.String("email", "");
            string linkman = Parse.String("linkman", "");
            string endtime = Parse.String("endtime", DateTime.Now.AddYears(1).ToString("yyyy-MM-dd"));

            if (user_id < 1)
                ParamError();

            Dictionary<string, object> dicUser = WAD.DAL.DaoUser.GetDetail(user_id, "id");
            if (dicUser == null || dicUser["id"] == DBNull.Value)
                JsonResult(1, "账号不存在");

            Dictionary<string, object> dic = DAOAgent.Get("vifo_users_agent", "userid_wjx=" + user_id, "userid_wjx");
            if (dic != null && dic["userid_wjx"] != DBNull.Value)
                JsonResult(1, "代理商已经存在");

            int count = DAOAgent.Add(user_id, sitename, phone, mobile, email, linkman, endtime);
            if (count > 0)
                JsonResult(0, "");
            else
                JsonResult(1, "添加失败");
        }

        [QD.Web.Ajax.AjaxMethod]
        public void Get()
        {
            int user_id = Parse.Int("user_id", 0);
            if (user_id < 1)
                JsonResult(1, "请填写编号");

            Dictionary<string, object> dic = DAOAgent.Get("vifo_users_agent", "userid_wjx=" + user_id, "CompanyName as sitename,linkman,balance,expiration_wjx as endtime");
            if (dic != null)
            {
                Dictionary<string, object> dicUser = WAD.DAL.DaoUser.GetDetail(user_id, "name");
                if (dicUser != null)
                    dic.Add("name", dicUser["name"]);
            }
            JsonResult(0, "", dic);
        }

        /// <summary>
        /// 代理商明细
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void Detail()
        {
            int user_id = Parse.Int("user_id", 0);
            if (user_id < 1)
                JsonResult(1, "请填写编号");

            Dictionary<string, object> dic = DAOAgent.Get("vifo_users_agent", "userid_wjx=" + user_id, "userid_wjx,status,Phone,price,CompanyName as sitename,linkman,balance,JoinTime,expiration_wjx as endtime");
            if (dic != null)
            {
                dic.Add("discount", GetDiscount(Convert.ToString(dic["price"])));
                dic.Remove("price");
            }
            JsonResult(0, "", dic);
        }

        [QD.Web.Ajax.AjaxMethod]
        public void GetList_Recoad()
        {
            int pageSize = 20;
            int page = Parse.Int("page", 1);
            int direction = Parse.Int("type", 0);
            int agentid = Parse.Int("agentid", 0);
            string where = "agentid=" + agentid;
            if (direction > 0)
                where += " and direction=" + direction;
            PageData dt = DAO.GetListPage("id,agentid,amount,balance,direction,itemid,remarks,userip,addtime", "id desc", page, pageSize, where, "Agent_Record");
            JsonResult(0, "", dt);
        }

        [QD.Web.Ajax.AjaxMethod]
        public void GetList_JiLu()
        {
            // select top 10 * from vIFO_Users_AgentJilu
            int pageSize = 20;
            int page = Parse.Int("page", 1);
            int agentid = Parse.Int("agentid", 0);
            string sitename = Parse.String("sitename");
            string where = "1=1";

            if (agentid > 0)
                where += " and agentuserid=" + agentid;

            if (!string.IsNullOrEmpty(sitename))
                where += " and sitename like '%" + QD.WX.Utill.Util.FilterSql(sitename) + "%";
            PageData dt = DAOAgentJiLu.GetPageList("agentuserid as agentid,UserName as sitename,type,UserID as adminid,createtime,contents", where, page, pageSize);
            if (dt.table.Rows.Count > 0)
            {
                List<Dictionary<string, object>> list = DAO_Union.GetList("select UserID, AdminName, TrueName From vIFO_Admin");
                for (int i = 0; i < dt.table.Rows.Count; i++)
                {
                    string userid = Convert.ToString(dt.table.Rows[i][""]);
                    for (int j = 0; j < list.Count; j++)
                    {
                        if (userid.Equals(Convert.ToString(list[j]["userid"])))
                        {
                            dt.table.Rows[i][""] = string.Format("{0}【{1}】");
                            break;
                        }
                    }
                }
            }
            JsonResult(0, "", dt);
        }

        /// <summary>
        /// 代理商充值(管理后台)
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void Pay()
        {
            int user_id = Parse.Int("user_id", 0);
            decimal money = Parse.Decimal("amount", 0);
            string name = Parse.String("name", "");
            string remarks = Parse.String("remarks", "");
            if (user_id < 1)
                ParamError();
            int itemid = 0;

            SqlParameter[] param ={
                                        new SqlParameter("@ToUserID",user_id),
                                        new SqlParameter("@ToUserName",name),
                                        new SqlParameter("@Money",money),
                                        new SqlParameter("@ItemID",itemid),
                                        new SqlParameter("@Remarks",remarks),
                                        new SqlParameter("@UserIP",Request.UserHostAddress)
                                      };
            int count = DAOAgent.ExecuteNonQuery_Stored("vIFO_User_MoneyTransfer_WJX", param);
            if (count > 0)
            {
                //添加充值记录(微街秀数据)
                //Dictionary<string, object> agent = DAOAgent.Get(UserId);
                Dictionary<string, object> agent = DAOAgent.Get(user_id);
                InsertDetail(0, user_id, money, Convert.ToDecimal(agent["balance"]), remarks);
                JsonResult(0, "成功");
            }
            if (count == -1)
                JsonResult(-1, "余额不足");
            else if (count == -3)
                JsonResult(-3, "充值失败,数据库执行报错");
            else
                JsonResult(500, "充值失败");
        }

        /// <summary>
        /// 业务系统：代理商提单统计
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void GetList_Tidan()
        {
            int id = Parse.Int("userid", 0);
            int page = Parse.Int("page", 1);
            int yewu_id = Parse.Int("yewu_id", 0);
            string siteName = Parse.String("sitename");
            string JoinTime = Parse.String("starttime", "");
            string Expiration = Parse.String("endtime", "");

            if (!CheckSign()) return;

            string where = "userid_wjx>0 ";
            if (id > 0)
                where += " and userid_wjx=" + id;

            if (yewu_id > 0)
                where += " and AllotUserName=" + yewu_id;

            if (!string.IsNullOrEmpty(siteName))
                where += " and companyName like '%" + QD.WX.Utill.Util.FilterSql(siteName) + "%'";

            if (!string.IsNullOrEmpty(JoinTime))
                where += " and JoinTime>='" + QD.WX.Utill.Util.FilterSql(JoinTime) + "'";

            if (!string.IsNullOrEmpty(Expiration))
                where += " and Expiration_wjx>='" + QD.WX.Utill.Util.FilterSql(Expiration) + "'";

            PageData dt = WAD.DAL.Union.DAOAgent.GetPageList("id,UserID,UserId_wjx,Balance,Phone,CellPhone,JoinTime,UpdateTime,CompanyName as sitename,Expiration_wjx as end_time,0 as counts", where, page, 10000);


            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < dt.table.Rows.Count; i++)
            {
                sb.Append("," + dt.table.Rows[i]["UserId_wjx"]);
            }

            if (sb.Length > 0)
            {
                //提单数
                List<Dictionary<string, object>> arr = DaoUser.GetList("counts>0 and agentid in(0" + sb.ToString() + ")", 10000, "v_user##tidan", "agentid,counts");

                for (int i = 0; i < dt.table.Rows.Count; i++)
                {
                    string key = Convert.ToString(dt.table.Rows[i]["UserId_wjx"]);
                    for (int j = 0; j < arr.Count; j++)
                    {
                        if (arr[j]["agentid"].ToString().Equals(key))
                        {
                            dt.table.Rows[i]["counts"] = arr[j]["counts"];
                            break;
                        }
                    }
                }
            }
            JsonResult(0, "", dt);
        }

        object GetDiscount(string price)
        {
            if (!string.IsNullOrEmpty(price))
            {
                //获取折扣
                //格式：<?xml version="1.0" encoding="utf-8"?><root><items id="1"><item cycleid="0" minimum="0" maximum="1" discount="30" type="0" /><item cycleid="0" minimum="2" maximum="3" discount="25" type="0" /><item cycleid="0" minimum="4" maximum="100" discount="20" type="0" /></items><items id="3"><item cycleid="0" minimum="0" maximum="1" discount="30" type="0" /><item cycleid="0" minimum="2" maximum="5" discount="25" type="0" /></items><items id="5"><item cycleid="0" minimum="0" maximum="20" discount="10" type="0" /></items></root>
                Regex r1 = new Regex("id=\"5\">([\\s\\S]+)</items>");
                if (r1.IsMatch(price))
                {
                    Regex r2 = new Regex("discount=\"([0-9]{0,3})\"");
                    string temp = r1.Match(price).Groups[1].Value;  //微街秀折扣列表
                    if (r2.IsMatch(temp))
                        return r2.Match(temp).Groups[1].Value;  //折扣(取其中一个)
                }
                return 0;   // 未设置折扣，当包年处理
            }
            return -1;      //折扣异常
        }

        int InsertDetail(int userid, int agentid, decimal price, decimal banlance, string remarks)
        {
            string sql = "insert into Agent_Record(agentid,amount,balance,direction,itemid,remarks,userip,addtime)values";
            sql += string.Format("({0},{1},{2},{3},{4},'{5}','{6}','{7}')", agentid, price, banlance, 1, userid, remarks, Request.UserHostAddress, DateTime.Now.ToString());
            return Convert.ToInt32(WAD.DAL.DAO.ExecuteNonQuery(sql));
        }


        bool CheckSign()
        {
            int sales = Parse.Int("sales", 100);
            int salesman = Parse.Int("salesman", 0);
            string uname = Parse.String("uname", "");
            string time = Parse.String("time", "");
            string ok_salesman = Parse.String("ok_salesman");
            string sign = Parse.String("sign", "");
            string sign1 = sign;   //Base64解码
            string sign2 = "sales=" + sales + "&uname=" + uname + "&salesman=" + salesman + "&time=" + time + "&sign=";
            string msg = "";
            if (uname.Length == 0 || time.Length == 0 || sign.Length == 0)
                msg = "参数错误";

            if (time.Length > 0)
            {
                try
                {
                    if (DateTime.Now.Subtract(QD.Utils.DateHelper.ToDate(time)).TotalMinutes > 120)
                        msg = "链接已过期,请到后台打开链接";
                }
                catch { msg = "参数错误"; }
            }

            if (msg.Length > 0)
            {
                JsonResult(11, msg);
                return false;
            }

            if (!Convert.ToString(sales + salesman).Equals(ok_salesman))
            {
                JsonResult(11, "签名不正确");
                return false;
            }

            return true;
        }
    }
}
